package com.bju.controller;

import com.bju.bean.User;
import com.bju.service.UserService;
import com.bju.utils.Result;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
public class UserController {
    @Resource
    private UserService userService;

    @PostMapping("/register")
    public Result register(@RequestBody User user) {
        try {
            userService.register(user);
            return Result.success("注册成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail(500, "注册失败");
        }
    }


    @GetMapping("/login")
    public Result login(String username, String password) {
        try {
            if (username == null || password == null || username.equals("") || password.equals("")) {
                return Result.fail(500, "请输入用户名和密码!!!");
            }
            User user = userService.login(username, password);
            if (user == null) {
                return Result.fail(500, "用户名密码不正确!!!");
            }
            System.out.println(user.getEmail() + "---------");
            return Result.success("登录成功!!!", user);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail(500, "登录失败");
        }
    }

    @GetMapping("/users")
    List<User> queryUsers() {
        return userService.queryUsers();
    }

    @RequestMapping(value = "/updateUser", consumes = MediaType.APPLICATION_JSON_VALUE)
    Result updateUser(@RequestBody User user) {
        try {
            System.out.println(user.toString());
            userService.updateUser(user);
            return Result.success("修改成功!!!");
        }catch (Exception e){
            e.printStackTrace();
            return Result.fail(500,"修改失败!!!");
        }

    }
}
